(function($){
$.widget('javui.javgraphicsView',{
    _create: function(){

    /* --------------- */
    /* Create elements
    /* --------------- */
    // Create container of graphics
    this._$container = $('<div></div>')
        .addClass('javui-javgraphicsView-container')
        .css({
            'height': this.options.height+'px',
            'width': this.options.width+'px',
            'background-color': this.options.bgkColor,
            })
        .attr('id','mapView')
        .appendTo(this.element);

    /*
    Drawing using Canvas
    */
    this._stage = new Kinetic.Stage({
        container: "mapView",
        width: this.options.width,
        height: this.options.height
    });
    
    this._meshLayer = new Kinetic.Layer();
    //this._tooltipLayer = new Kinetic.Layer();  
        
    /**/        
    },

    options: {
        height: 500,
        width: 500,
        //bgkColor: '#F7EFEF'
        bgkColor: '#FFFFCC'
    },

    getCanvas: function(){
       return this._stage; 
    },
    
    showGrid: function(){
    // Get data
    var dx = parseFloat($('#relief-dx').val());
    var dy = parseFloat($('#relief-dy').val());
    var Lx = this._$container.width();
    var Ly = this._$container.height();
    var nx = parseInt(Lx/dx);
    var ny = parseInt(Ly/dy);
    var gridWidth = 1.0;
    /*
    Drawing using Canvas
    */
    this._stage.clear();
    var mesh = new Array();
    
    var iobj = -1;
    for(i=0;i<nx;i++){
        for(j=0;j<ny;j++){
            iobj += 1;
            mesh[iobj] = new Kinetic.Rect({
                x: i*dx+gridWidth/2,
                y: j*dy+gridWidth/2,
                width: dx-gridWidth,
                height: dy-gridWidth,
                fill: "#00D2FF",
                name: 'cell-'+i+'-'+j,
                alpha: 0.5
            });
            
          
            // add the shape to the layer
            this._meshLayer.add(mesh[iobj]);
        }
    }
    
 
    //tooltipLayer.listen(false);
    //this._tooltipLayer.add(this._tooltip);
    //this._stage.add(this._tooltipLayer);
    
    // add the layer to the stage
    this._stage.add(this._meshLayer);
    
    return mesh;
    /**/
    },

    _getMousePos: function (canvas, evt){

    // get canvas position
    var obj = canvas;
    var top = 0;
    var left = 0;
    while (obj && obj.tagName != 'BODY') {
        top += obj.offsetTop;
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }

    // return relative mouse position
    var mouseX = evt.clientX - left + window.pageXOffset;
    var mouseY = evt.clientY - top + window.pageYOffset;
    return {
        x: mouseX,
        y: mouseY
    };
    // End function
    },

    _open: function(){
    },

    _close: function(){
    },

    destroy: function(){
    }
});
})(jQuery);
